package com.sm.li.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.sm.li.common.exception.ApiException;
import com.sm.li.common.http.AxiosResult;
import com.sm.li.common.http.AxiosStatus;
import com.sm.li.common.page.PageBean;
import com.sm.li.common.perm.HasPerm;
import com.sm.li.common.valid.group.AddGroup;
import com.sm.li.common.valid.group.UpdateGroup;
import com.sm.li.controller.base.BaseController;
import com.sm.li.dto.AdminDTO;
import com.sm.li.entity.Admin;
import com.sm.li.query.AdminQuery;
import com.sm.li.service.AdminService;

import com.sm.li.transfer.AdminTransfer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.PublicKey;
import java.util.List;

@RestController
@RequestMapping("admin")
public class AdminController extends BaseController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    //    @GetMapping
//    public AxiosResult<List<AdminDTO>> list() {
//        return AxiosResult.success(adminService.list());
//    }
    @GetMapping("{id}")
    public AxiosResult<AdminDTO> findById(@PathVariable Long id) {
        AdminDTO adminDTO= adminService.getAdminAndRolesByAdmin(id);
        return AxiosResult.success(adminDTO);
    }

    //分页条件查询
    @GetMapping("searchPage")
    public AxiosResult<PageBean<AdminDTO>> searchPage(AdminQuery AdminQuery) {
        //开启分页
        System.out.println(AdminQuery);
        PageHelper.startPage(AdminQuery.getCurrentPage(), AdminQuery.getPageSize());
        PageBean<AdminDTO> pageBean = adminService.searchPage(AdminQuery);
        return AxiosResult.success(pageBean);
    }

    //@Valid 开启后端表单校验
    @PostMapping
    @HasPerm(permSign = "system:admin:add")
    public AxiosResult<Void> add(@Validated(AddGroup.class) @RequestBody Admin Admin) {

      boolean b=  adminService.hasAdminWithAccountPhoneEmail(Admin);
        if (b){
            //存在
            throw new  ApiException(AxiosStatus.ADMIN_EXIST);
        }
        Admin.setAdminPassword(bCryptPasswordEncoder.encode("123"));

        int row= adminService.addAdminAndRole(Admin);
        return toAxios(row);
    }

    @PutMapping
    @HasPerm(permSign = "system:admin:edit")
    public AxiosResult<Void> update(@Validated(UpdateGroup.class) @RequestBody Admin Admin) {
       int row=adminService.updateAdminAndRole(Admin);
        return toAxios(row);

    }

    @DeleteMapping("{id}")
    @HasPerm(permSign = "system:admin:delete")
    public AxiosResult<Void> deleteById(@PathVariable Long id) {
        return toAxios(adminService.deleteAdminAndRoles(id));

    }

    @DeleteMapping("batch/{ids}")
    @HasPerm(permSign = "system:admin:batch")
    public AxiosResult<Void> batchDeleteById(@PathVariable List<Long> ids) {
        return toAxios(adminService.batchDeleteAdminAndRole(ids));

    }

    //员工导出表格（以下代码百度EasyExcel里获取）
    @GetMapping("exportExcel")
    public void exportExcel(HttpServletResponse response) throws Exception{
        List<Admin> list = adminService.list();
        list.forEach(admin -> {
            admin.setSex(admin.getGender()==0?"男":admin.getGender()==1?"女":"保密");
            try {
                admin.setUrl(new URL(admin.getAdminAvatar()));
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        });
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("员工信息表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Admin.class).sheet("员工信息").doWrite(list);

    }

}
